<script setup lang="jsx">
import { reactive, ref } from 'vue';
import { UUID } from 'uuidjs';

import { parseTime } from '@/utils';
import { erpsyncmespubtechnology, pubtechnologySelect } from '@/service/api/modules/erp';
import { get, post, postFormData } from '@/service/api/api';
import Modal from '@/components/common/modal.vue';
import Form from '@/components/common/form.vue';
import Search from './modules/search.vue';
const searchParams = ref({
  time: null
});
const formState = ref({});
const fileList = ref([]);
const baseUrl = import.meta.env.VITE_SERVICE_BASE_URL;
const pagination = reactive({
  current: 1,
  pageSize: 200,
  showSizeChanger: true,
  pageSizeOptions: ['50', '100', '200', '300', '500'],
  showQuickJumper: true,
  showTotal: total => {
    return `共${total}条`;
  },
  total: 0,
  onChange: async (current, size) => {
    pagination.current = current;
    pagination.pageSize = size;
    getData();
  }
});

const columns = ref([
  {
    key: 'index',
    dataIndex: 'index',
    title: '序号',
    width: 100,
    align: 'center',
    checked: true
  },
  {
    key: 'phone',
    dataIndex: 'phone',
    title: '手机号码',
    width: 150,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'phone2',
    dataIndex: 'phone2',
    title: '手机号码2',
    width: 150,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'phone3',
    dataIndex: 'phone3',
    title: '手机号码3',
    width: 150,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'phone4',
    dataIndex: 'phone4',
    title: '手机号码4',
    width: 150,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'passOver',
    dataIndex: 'passOver',
    title: '上传文件',
    width: 200,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      return (
        <A color={'blue'} onClick={() => exeData(record)}>
          {record.filePath}
        </A>
      );
    }
  },
  {
    key: 'createTime',
    dataIndex: 'createTime',
    title: '上传时间',
    width: 180,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'createUser',
    dataIndex: 'createUser',
    title: '修改人',
    width: 100,
    align: 'center',
    checked: true,
    ellipsis: true
  }
]);
const crDatas = ref({});
const detailsVisibleQrcode = ref(false);
const detailsVisibleQrcode1 = ref(false);
const tableData = ref([]);
const loading = ref(false);
const defaultExpandedRowKeys = ref([]);

function getData() {
  loading.value = true;
  const params = {};

  if (searchParams.value.time?.[0]) {
    params.startTime = searchParams.value.time[0];
    params.endTime = searchParams.value.time[1];
  }

  get('qms/hr/annualTestReport/potableWater/list', {
    pageSize: pagination.pageSize,
    pageNum: pagination.current,
    ...params
  })
    .then(({ data, error }) => {
      if (!error) {
        console.log(data, 123);
        params.value = {};
        data.list.forEach((item, index) => {
          item.index = index + 1;
        });
        tableData.value = data.list;
        pagination.total = data.total;
      }
    })
    .finally(() => {
      loading.value = false;
    });
}
function manualSyncing() {
  crDatas.value = {};
  detailsVisibleQrcode.value = true;
}
function deleteData1() {
  if (!selectedRowKeys.value) {
    window.$message?.error('请先选择数据');
  } else {
    const arr = [];

    arr.push(selectedRowKeys.value);

    post('qms/hr/annualTestReport/deleteBatch', selectedRowKeys.value).then(res => {
      if (!error) {
        window.$message?.success('删除成功!');
        selectedRowKeys.value = [];
        getData();
      }
    });
  }
}
function boundUpdata() {
  const fromData = new FormData();
  fromData.append('file', formState.value.file);
  fromData.append('phone', formState.value.phone);
  fromData.append('phone2', formState.value.phone2);
  fromData.append('phone3', formState.value.phone3);
  fromData.append('phone4', formState.value.phone4);
  console.log(fromData);
  postFormData('/qms/hr/annualTestReport/potableWater/add/new', fromData).then(res => {
    if (!error) {
      detailsVisibleQrcode.value = false;
      window.$message?.success(res.data.msg);
      getData();
      formState.value = {};
    }
  });
  // erpsyncmespubtechnology(crDatas.value).then(({ data, error }) => {
  //   if (!error) {
  //     window.$message?.success('手动同步成功');
  //     detailsVisibleQrcode.value = false;
  //     getData();
  //   }
  // });
}
getData();

function search() {
  pagination.current = 1;
  getData();
}
const pdfSrc = ref('');
function exeData(row) {
  pdfSrc.value = `${baseUrl}/qms/hr/annualTestReport/preview?filePath=${row.filePath}`;
  // pdfSrc.value = `${baseUrl}/collection-management/equipment-alarm-info`;
  detailsVisibleQrcode1.value = true;
}
const selectedRowKeys = ref([]);
const currentRowId = ref(null);
const customRow = record => {
  return {
    style: {
      background: record.uid === currentRowId.value ? '#BAEAFA' : ''
    },
    class: record.uid === currentRowId.value ? 'jl-table-row-selected' : '',
    onClick: () => {
      currentRowId.value = record.uid;
    }
  };
};
function tableSelectChange(val) {
  selectedRowKeys.value = val;
  console.log(selectedRowKeys.value.join(','));
}

const handleChange = info => {
  if (info.file.status !== 'uploading') {
    // console.log(info.file, info.fileList);
    formState.value.file = info.file;
  }
  if (info.file.status === 'done') {
    message.success(`${info.file.name} file uploaded successfully`);
  } else if (info.file.status === 'error') {
    message.error(`${info.file.name} file upload failed.`);
  }
};
function handleBeforeUpload(file) {
  // 在这里可以添加你的逻辑判断，比如检查文件类型、大小等
  // 如果希望阻止上传，可以返回一个被拒绝的Promise或直接返回false（但推荐使用Promise以保持一致性）
  return new Promise((resolve, reject) => {
    // 假设我们总是阻止上传

    reject(false); // 阻止上传
  });
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <Search v-model:model="searchParams" @reset="search()" @search="search()" />
    <ACard
      :bordered="false"
      :body-style="{ flex: 1, overflow: 'hidden' }"
      class="table-card flex-col-stretch sm:flex-1-hidden card-wrapper"
    >
      <template #title>
        <AButton type="primary" size="small" ghost class="mini-btn mr-8px" @click="manualSyncing">
          <span class="ml-3px">新增</span>
        </AButton>
        <AButton type="primary" size="small" ghost class="mini-btn mr-8px" @click="deleteData1">
          <span class="ml-3px">删除</span>
        </AButton>
      </template>
      <template #extra>
        <TableColumnSetting v-model:columns="columns" />
      </template>
      <STable
        :columns="columns"
        :data-source="tableData"
        size="small"
        bordered
        :loading="loading"
        :default-expanded-row-keys="defaultExpandedRowKeys"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: tableSelectChange }"
        row-key="id"
        :default-expand-all-rows="true"
        :scroll="{ x: 'auto', y: 'auto' }"
        :pagination="pagination"
        class="h-full"
        :custom-row="customRow"
        :row-height="23"
      />
      <Modal
        v-model:visible="detailsVisibleQrcode1"
        :destroy-on-close="true"
        title="预览生活饮用水检验文件"
        width="700px"
      >
        <iframe
          :src="pdfSrc"
          width="100%"
          style="min-height: 600px; min-width: 600px"
          height="100%"
          frameborder="0"
        ></iframe>
        <template #footer>
          <div class="modal-footer">
            <AButton @click="detailsVisibleQrcode1 = false">关闭</AButton>
          </div>
        </template>
      </Modal>
      <Modal v-model:visible="detailsVisibleQrcode" :destroy-on-close="true" title="生活饮用水检验新增" width="700px">
        <div class="event-form">
          <AForm :model="formState" name="basic" :label-col="{ span: 6 }">
            <ARow :gutter="24">
              <ACol :span="12">
                <AFormItem label="手机号码" name="phone">
                  <AInput v-model:value="formState.phone" />
                </AFormItem>
              </ACol>
              <ACol :span="12">
                <AFormItem label="手机号码" name="phone2">
                  <AInput v-model:value="formState.phone2" />
                </AFormItem>
              </ACol>
              <ACol :span="12">
                <AFormItem label="手机号码" name="phone3">
                  <AInput v-model:value="formState.phone3" />
                </AFormItem>
              </ACol>
              <ACol :span="12">
                <AFormItem label="手机号码" name="phone4">
                  <AInput v-model:value="formState.phone4" />
                </AFormItem>
              </ACol>
              <ACol :span="24">
                <AFormItem label="信息上传" name="username" :label-col="{ span: 0 }">
                  <AUpload
                    v-model:file-list="fileList"
                    :before-upload="handleBeforeUpload"
                    :max-count="1"
                    name="file"
                    @change="handleChange"
                  >
                    <AButton>
                      <UploadOutlined></UploadOutlined>
                      点击上传
                    </AButton>
                  </AUpload>
                </AFormItem>
              </ACol>
            </ARow>
          </AForm>
        </div>

        <template #footer>
          <div class="modal-footer">
            <AButton @click="detailsVisibleQrcode = false">关闭</AButton>
            <AButton type="primary" @click="boundUpdata">保存</AButton>
          </div>
        </template>
      </Modal>
    </ACard>
  </div>
</template>

<style></style>
